package vip.liux.backend.infrastructure.algorithm;

public class Search {

    public static final int[] ARRAY = {3, 5, 11, 17, 21, 23, 28, 30, 32, 50, 64, 78, 81, 95, 101};

    public static int binSearch(int[] array, int target) {

        if (array == null || array.length == 0) {
            return -1;
        }

        int first = array[0];
        int last = array[array.length - 1];

        if (target < first || target > last) {
            return -1;
        }

        int mid = array.length / 2;
        if (array[mid] == target) {
            return mid;
        }

        int startIndex = 0;
        int endIndex = array.length - 1;

        while (startIndex <= endIndex) {
            mid = (startIndex + endIndex) / 2;
            if (array[mid] == target) {
                return mid;
            } else if (array[mid] < target) {
                startIndex = mid + 1;
            } else {
                endIndex = mid - 1;
            }
        }
        return -1;
    }
}
